package com.chenyu.upload.util;

import com.chenyu.upload.constant.QiNiuConstant;
import com.qiniu.common.QiniuException;
import com.qiniu.processing.OperationManager;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 七牛云相关操作工具类
 *
 * @author yu_chen
 * @date 2018年4月2日17:02:07
 */
public class QiniuOperateUtil {

    public static void main(String[] args) {
        String persist_ = StringUtils.substringAfter("persist_asdoieqwe.jpg", "persist_");
        System.out.println(persist_);
    }

    private static Auth auth = Auth.create(QiNiuConstant.ACCESS_KEY,
            QiNiuConstant.SECRET_KEY);
    private BucketManager bucketManager = new BucketManager(auth);

    /**
     * 简单上传，使用默认策略
     *
     * @return
     */
    public String getSimpleToken() {
        String token = auth.uploadToken(QiNiuConstant.OPEN_BUCKET);
        return token;
    }

    /**
     * 覆盖上传
     *
     * @param key
     * @return
     */
    public String getCoverToken(String key) {
        String token = auth.uploadToken(QiNiuConstant.OPEN_BUCKET, key);
        return token;
    }

    /**
     * 获取并且持久化
     *
     * @return
     */
    public String getAndPersist(String fileKey) throws QiniuException {
        //数据处理指令，支持多个指令
        String saveJpgEntry = String.format("%s:" + QiNiuConstant.PERSIST_PREFIX + fileKey, QiNiuConstant.PRIVATE_BUCKET);
        String avthumbMp4Fop = String.format("imageView2/2/w/1000|saveas/%s", UrlSafeBase64.encodeToString(saveJpgEntry));
        //将多个数据处理指令拼接起来
        //...其他参数参考类注释
        //构建持久化数据处理对象
        OperationManager operationManager = new OperationManager(auth);
        String persistentId = operationManager.pfop(QiNiuConstant.PRIVATE_BUCKET, fileKey, avthumbMp4Fop);
        //插入数据到数据库

        //可以根据该 persistentId 查询任务处理进度
        System.out.println(persistentId);
        //解析 operationStatus 的结果
        return persistentId;
    }

    /**
     * 获取文件信息
     *
     * @param key 文件的KEy
     * @return
     */
    public FileInfo getFileInfo(String key) {
        FileInfo fileInfo = null;
        try {
            fileInfo = bucketManager.stat(QiNiuConstant.OPEN_BUCKET, key);
        } catch (QiniuException e) {

        }
        return fileInfo;
    }

    /**
     * 获取公共空间上传token
     *
     * @return
     */
    public String getUploadToken() {
        return auth
                .uploadToken(
                        QiNiuConstant.OPEN_BUCKET,
                        null,
                        3600 * 24,
                        new StringMap()
                                .putNotEmpty(
                                        "returnBody",
                                        "{\"key\": $(key), \"hash\": $(etag), \"width\": $(imageInfo.width), \"height\": $(imageInfo.height)}"));
    }

    /**
     * @return
     */
    public String getPrivateUploadToken() {
        return auth
                .uploadToken(
                        QiNiuConstant.PRIVATE_BUCKET,
                        null,
                        3600 * 24,
                        new StringMap()
                                .putNotEmpty(
                                        "returnBody",
                                        "{\"key\": $(key), \"hash\": $(etag), \"width\": $(imageInfo.width), \"height\": $(imageInfo.height)}"));
    }

    /**
     * 获取下载token
     *
     * @param url
     * @return
     */
    public String getDownloadToken(String url) {
        // 默认有效时长：3600秒
        return auth.privateDownloadUrl(url, 3600 * 240);
    }

    /**
     * 移动单个文件
     *
     * @param oldBucket
     * @param newBucket
     * @param oldKey
     * @param newKey
     * @return
     */
    public boolean CopySingleFile(String oldBucket, String newBucket,
                                  String oldKey, String newKey) {
        try {
            bucketManager.copy(oldBucket, oldKey, newBucket, newKey);
            return true;
        } catch (QiniuException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 上传文件到公开空间
     *
     * @param data     上传文件到公开空间
     * @param fileName 文件名
     */
    public void uploadFileToOpenSpace(byte[] data, String fileName) {
        QiniuOperateUtil operate = new QiniuOperateUtil();
        String token = operate.getUploadToken();
        UploadManager upload = new UploadManager();
        try {
            upload.put(data, fileName, token);
        } catch (QiniuException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 上传文件到公 私有
     *
     * @param data     上传文件到公开空间
     * @param fileName 文件名
     */
    public void uploadFileToPrivateSpace(byte[] data, String fileName) {
        QiniuOperateUtil operate = new QiniuOperateUtil();
        String token = operate.getPrivateUploadToken();
        UploadManager upload = new UploadManager();
        try {
            upload.put(data, fileName, token);
        } catch (QiniuException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 上传文件到公 私有
     *
     * @param file     文件
     * @param fileName 文件名
     */
    public void uploadFileToPrivateSpaceFile(File file, String fileName) {
        QiniuOperateUtil operate = new QiniuOperateUtil();
        String token = operate.getPrivateUploadToken();
        UploadManager upload = new UploadManager();
        try {
            upload.put(file, fileName, token);
        } catch (QiniuException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 上传文件到公开空间
     *
     * @param filePath 文件本地路径
     * @param fileName 文件名
     */
    public void uploadFileToOpenSpace(String filePath, String fileName) {
        QiniuOperateUtil operate = new QiniuOperateUtil();
        String token = operate.getUploadToken();
        UploadManager upload = new UploadManager();
        try {
            upload.put(filePath, fileName, token);
        } catch (QiniuException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 上传文件到公开空间
     *
     * @param filePath 文件本地路径
     * @param fileName 文件名
     */
    public void uploadFileToOpenSpace(File file, String fileName) {
        QiniuOperateUtil operate = new QiniuOperateUtil();
        String token = operate.getUploadToken();
        UploadManager upload = new UploadManager();
        try {
            upload.put(file, fileName, token);
        } catch (QiniuException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 上传文件到私有空间
     *
     * @param filePath
     * @param fileName
     */
    public void uploadFileToPrivateSpace(String filePath, String fileName) {
        QiniuOperateUtil operate = new QiniuOperateUtil();
        String token = operate.getPrivateUploadToken();
        UploadManager upload = new UploadManager();
        try {
            upload.put(filePath, fileName, token);
        } catch (QiniuException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 获取图片信息
     *
     * @param url
     * @return
     */
    public String sentHttpRequestToGetImageInfo(String url) {

        String result = "";
        BufferedReader in = null;
        try {
            while (true) {
                URL obj = new URL(url);
                HttpURLConnection con = (HttpURLConnection) obj.openConnection();
                con.setRequestMethod("GET");
                con.setRequestProperty("accept", "*/*");
                con.setDoOutput(true);
                con.setDoInput(true);
                int code = con.getResponseCode();
                if (!(code == 500)) {
                    // 系统没有发生错误，则获取返回信息，并返回
                    in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    String line;
                    while ((line = in.readLine()) != null) {
                        result += line;
                    }
                    break;
                }
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 下载七牛云私有云图片
     * 并将图片 转化成byte数组   格式为jpg格式
     *
     * @param address 图片私有云地址
     * @author 杨岳
     */
    public byte[] bufferedImageToByteArray(String address) {
        QiniuOperateUtil qiniu = new QiniuOperateUtil();
        String firstPicUrl = qiniu.getDownloadToken(address);
        byte[] bytes = null;
        //转换成 byte
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            BufferedImage picBi = ImageIO.read(new URL(firstPicUrl));
            ImageIO.write(picBi, "jpg", byteArrayOutputStream);
            bytes = byteArrayOutputStream.toByteArray();
            return bytes;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param fromBucket
     * @param fromKey
     * @param toBucket
     * @param toKey
     */
    public static void privateToPublic(String fromBucket, String fromKey, String toBucket, String toKey) {
        BucketManager bucketManager = new BucketManager(auth);
        try {
            bucketManager.copy(fromBucket, fromKey, toBucket, toKey);
        } catch (QiniuException ex) {
            System.out.println("失败");

        }
    }
}
